//
//  ShopDetailViewController.swift
//  quizDemo
//
//  Created by LiuXing on 2017/9/10.
//  Copyright © 2017年 quiz. All rights reserved.
//

import UIKit

private let reuseIdentifier = "ShopDetailCollectionViewCell"
class ShopDetailViewController: UIViewController {
    
    var pic: [String]! = ["game1", "game2", "game3", "game4", "game5"]
    var name: [String]! = ["Monster Hunter Generations", "Uncharted 4：A Thief’s End", "The lost child", "METAL GEAR SOLID", "Horizon：Zero Dawn"]
    var info: [String]! = ["This positioning in the super MHF ornate style, new map, new, monster four big play, past and past map On the points to come back in the game, also at the scene saw the coco and knot cloud village, village, pockets etc. We are familiar with the stronghold.",
                           "Game set in the original forest, tropical rain forest, desert plateau hinterland, snow mountain, ancient ruins, presents in the movie.Hero Nathan Drake (Nathan Drake) to face all kinds of enemies, finally found the treasure",
                           "Magazine writers, hawk who decided to start tracking continuous suicides occur in shinjuku station, in the survey, all of a sudden they were shadows on the stage from the month drops, but at this juncture thought mystery of beauty",
                          " Metal gear solid V: phantom pain occurred in 1984, as also in the game and reality of the war in Afghanistan.Despite the games in general is the same as the reality, but can be found within the game player to weapons and technology should be far more advanced than the reality of the cold war.Not only is the metal gear solid itself, other military ","The horizon: dawn is a about the end of the mechanical dinosaur, cavemen and announcement of third-person action game, game set in the distant future, human civilization has ended, there was damaged planet is rebuilding, optimum population, humans are not highly developed intelligent machines held the top of the food chain"]
    var price: [String]! = ["￥100", "￥150", "￥200", "￥250", "￥300"]

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        edgesForExtendedLayout = UIRectEdge.init(rawValue: 0)
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.left.right.equalTo(view)
            make.top.equalTo(view.snp.top).offset(20)
            make.height.equalTo(171)
        }
        view.addSubview(namelabel)
        namelabel.snp.makeConstraints { (make) in
            make.left.equalTo(view.snp.left).offset(20)
            make.top.equalTo(collectionView.snp.bottom).offset(20)
        }
        namelabel.text = name[0]
        
        view.addSubview(infolabel)
        infolabel.snp.makeConstraints { (make) in
            make.left.equalTo(view.snp.left).offset(20)
            make.right.equalTo(view.snp.right).offset(-20)
            make.top.equalTo(namelabel.snp.bottom).offset(20)
        }
        infolabel.text = info[0]
        
        view.addSubview(pricelabel)
        pricelabel.snp.makeConstraints { (make) in
            make.left.equalTo(view.snp.left).offset(20)
            make.top.equalTo(infolabel.snp.bottom).offset(20)
        }
        
        pricelabel.text = price[0]
    }
    
    private lazy var flowLayout: FlowLayout = {
        let layout = FlowLayout()
        layout.itemSize = CGSize(width: 170, height: 171)
        layout.scrollDirection = .horizontal;
        let margin = (ScreenWidth - 170) * 0.5;
        print(margin)
        layout.sectionInset = UIEdgeInsetsMake(0, margin, 0, margin);
        // 设置最小行间距
        layout.minimumLineSpacing = 25;
        return layout
    }()
    
    lazy var collectionView: UICollectionView = {
        let collection = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.flowLayout)
        collection.register(UINib.init(nibName: "ShopDetailCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
        collection.dataSource = self
        collection.delegate = self
        collection.backgroundColor = UIColor.white
        return collection
    }()
    
    lazy var namelabel: UILabel = {
        let namelabel = UILabel()
        return namelabel
    }()
    lazy var infolabel: UILabel = {
        let namelabel = UILabel()
        namelabel.numberOfLines = 0
        return namelabel
    }()
    lazy var pricelabel: UILabel = {
        let namelabel = UILabel()
        namelabel.textColor = UIColor.red
        namelabel.font = UIFont.systemFont(ofSize: 25)
        return namelabel
    }()
    

    @IBAction func cartButtonClick(_ sender: Any) {
        let alertView = UIAlertView.init(title: "", message: "Add SHop Cart Success", delegate: self, cancelButtonTitle: "confirm")
        alertView.show()
    }
}

extension ShopDetailViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pic.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ShopDetailCollectionViewCell
        cell.image = pic[indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)
        namelabel.text = name[indexPath.item]
        infolabel.text = info[indexPath.item]
        pricelabel.text = price[indexPath.item]
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        print("\(collectionView.indexPathsForVisibleItems)")
        print("\(collectionView.indexPathsForVisibleItems.count)")
        if collectionView.indexPathsForVisibleItems.count == 2 { //
            let indepath1 = collectionView.indexPathsForVisibleItems[0] as NSIndexPath
            let indepath2 = collectionView.indexPathsForVisibleItems[1] as NSIndexPath
            if indepath1.item == 0 || indepath2.item == 0 {
                namelabel.text = name[0]
                infolabel.text = info[0]
                pricelabel.text = price[0]
            } else {
                namelabel.text = name[4]
                infolabel.text = info[4]
                pricelabel.text = price[4]
            }
        } else {
            let indepath1 = collectionView.indexPathsForVisibleItems[0] as NSIndexPath
            let indepath2 = collectionView.indexPathsForVisibleItems[1] as NSIndexPath
            let indepath3 = collectionView.indexPathsForVisibleItems[2] as NSIndexPath
            let array = [indepath1.item, indepath2.item, indepath3.item]
            let resultArray = quickSort(data: array)
            namelabel.text = name[resultArray[1]]
            infolabel.text = info[resultArray[1]]
            pricelabel.text = price[resultArray[1]]
        }
    }
    
    func quickSort(data:[NSInteger]) -> [NSInteger] {
        if data.count <= 1 {
            return data
        }
        var left:[NSInteger] = []
        var right:[NSInteger]=[]
        let pivot:NSInteger=data[data.count-1]
        for index in 0..<data.count-1 {
            if data[index]<pivot {
                left.append(data[index])
            }else{
                right.append(data[index])
            }
        }
        var result=quickSort(data: left)
        result.append(pivot)
        let rightResult=quickSort(data: right)
        result.append(contentsOf: rightResult)
        return result
    }
}

extension ShopDetailViewController: UIAlertViewDelegate {
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
        navigationController?.popViewController(animated: true)
    }
}
